<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		*{
			margin: 0;padding: 0;
		}
		#wrap{
			width: 800px;height: 300px;border: 1px solid #000;position: relative;margin: 50px auto;
		}
		#wall{
			width: 50px;height: 100px;position: absolute;background: red;right: 50px;top: 100px;
		}
		#blood{
			width: 10px;height: 100px;border: 1px solid #000;position: absolute;right:30px;top: 100px; box-sizing: border-box;
		}
		#ball{
			width: 30px;height: 30px;border-radius: 50%;background: cyan;position: absolute;left: 0;top: 135px;
		}
		.sblood{
			width: 10px;height: 10px;background: red;border: 1px solid #000;box-sizing: border-box;
		}

	</style>
</head>
<body>
	<div id="wrap">
		<div id="wall"></div>
		<div id="blood"></div>
	</div>
</body>
<script type="text/javascript">
	var wrap = document.getElementById('wrap');
	var wall = document.getElementById('wall');
	var blood = document.getElementById('blood');

	// 补血
	var sblood;
	for(var i=0;i<10;i++){
		sblood = document.createElement('div');
		sblood.className = 'sblood';
		blood.appendChild(sblood);
	}
	// 添加血属性
	wall.blood = 10;

	// 创建小球
	function createBall(){
		var ball = document.createElement('div');
		ball.id = 'ball';
		wrap.appendChild(ball);


		var timer = null;
		var offValue = ball.offsetLeft;
		ball.move = function (){

			timer = setInterval(function(){
				offValue+=10;
				ball.style.left = offValue+'px';

				//判断是否撞墙
				if (offValue >= wall.offsetLeft-ball.offsetWidth) {
					wall.blood--;
					if (wall.blood>=0) {
						blood.childNodes[10-wall.blood-1].style.opacity = 0;
						ball.clear();
					}
					if (wall.blood<=0) {
						wall.remove();
						blood.remove();
					}
				}

				//墙没有的时候才会撞到这
				if (offValue >= wrap.offsetWidth-ball.offsetWidth) {
					ball.clear();
				}
				
			},10);
		}
		ball.clear = function (){
			//1.
			ball.remove();
			// wrap.removeChild(ball);
			clearInterval(timer);
		}
	
	}

	wrap.onclick = function(){
		createBall();
	}
</script>
</html>